package com.lyn.tencent_health_code.service;

import com.alibaba.fastjson.JSONObject;
import com.lyn.tencent_health_code.config.HealthCodeConfig;
import com.lyn.tencent_health_code.entity.*;
import com.lyn.tencent_health_code.utils.RedisUtil;
import com.lyn.tencent_health_code.utils.TextUtils;
import com.tencent.healthcard.impl.HealthCardServerImpl;
import com.tencent.healthcard.model.CommonIn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author almost
 */
@Service
public class HealthCodeService {
    private Logger logger = LoggerFactory.getLogger(HealthCodeService.class);
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取Token
     *
     * @return
     * @throws Exception
     */
    public String getHealthCodeToken() throws Exception {
        Object appToken = redisUtil.get("appToken");
        String token = null;
        if (appToken instanceof String) {
            token = (String) appToken;
        }
        if (!TextUtils.isEmpty(token)) {
            return token;
        }
        //设置连接超时5s，请求超时10s，默认二者均为10s
        HealthCardServerImpl healthCard = new HealthCardServerImpl(HealthCodeConfig.APP_SECRET, 5, 10);
        //另外一种方式设置连接、请求超时时间
        healthCard.setConnectTimeout(5);
        healthCard.setReadTimeout(10);
        //构造公共输入参数commonIn
        String requestId = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        CommonIn commonIn = new CommonIn("", requestId, HealthCodeConfig.HOSPITAL_NUMBER, 0);
        //调用接口
        JSONObject appTokenObj = healthCard.getAppToken(commonIn, HealthCodeConfig.APP_ID);
        //可以单独对某一个方法设置连接、请求超时时间，单位均为s，连接超时时间3s，请求超时时间20s
        //JSONObject appTokenObj2 = healthCard.getAppToken(commonIn, appId, 3, 20);
        String rsp = appTokenObj.getString("rsp");
        HealthCodeToken healthCodeToken = JSONObject.toJavaObject(JSONObject.parseObject(rsp), HealthCodeToken.class);
        boolean success = redisUtil.set("appToken", healthCodeToken.getAppToken(), healthCodeToken.getExpiresIn());
        if (success) {
            return healthCodeToken.getAppToken();
        }
        return null;
    }

    /**
     * 验证健康码结果
     *
     * @param verifyHealthCode
     * @throws Exception
     */
    public PersonInfo verifyHealthCode(VerifyHealthCode verifyHealthCode) throws Exception {
        HealthCardServerImpl healthCard = new HealthCardServerImpl(HealthCodeConfig.APP_SECRET);
        //构造公共输入参数commonIn
        String requestId = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        CommonIn commonIn = new CommonIn(getHealthCodeToken(), requestId, HealthCodeConfig.HOSPITAL_NUMBER, 0);
        //调用接口
        JSONObject healthCardInfoRsp = healthCard.getHealthCardByQRCode(commonIn, verifyHealthCode.getQrCode());
        HealthCodeResult healthCodeResult = healthCardInfoRsp.toJavaObject(HealthCodeResult.class);
        if (healthCodeResult != null && healthCodeResult.getCommonOut().getResultCode() == 0) {
            if (healthCodeResult.getRsp() != null) {
                Rsp rsp = verifyHealthCodeColor(healthCodeResult.getRsp().getCard());
                PersonInfo personInfo = new PersonInfo();
                personInfo.setName(healthCodeResult.getRsp().getCard().getName());
                personInfo.setIdCard(healthCodeResult.getRsp().getCard().getIdCard());
                personInfo.setColor(rsp.getColor());
                switch (rsp.getColor()) {
                    case 1:
                        personInfo.setColorName("green");
                        break;
                    case 2:
                        personInfo.setColorName("yellow");
                        break;
                    case 3:
                        personInfo.setColorName("red");
                        break;
                    default:
                        personInfo.setColorName("");
                        break;
                }
                return personInfo;
            }
        }
        return null;
    }

    /**
     * 验证健康码颜色
     */
    private Rsp verifyHealthCodeColor(Card card) throws Exception {
        if (card == null) {
            return null;
        }
        HealthCardServerImpl healthCard = new HealthCardServerImpl(HealthCodeConfig.APP_SECRET);
        //构造公共输入参数commonIn
        String requestId = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        CommonIn commonIn = new CommonIn(getHealthCodeToken(), requestId, HealthCodeConfig.HOSPITAL_NUMBER, 0);
        //构造请求参数req
        JSONObject dynamicQRCode = healthCard.getDynamicQRCode(commonIn,
                card.getHealthCardId(),
                card.getIdType(),
                card.getIdNumber(),
                "0");

        HealthCodeResult healthCodeResult = dynamicQRCode.toJavaObject(HealthCodeResult.class);
        return healthCodeResult.getRsp();
    }
}
